import {token} from '../common.js';


let reqDefault = {
	token: token,
	pages: {
		page: 1,
		page_number: 10
	}
}

let template = require('../plugins/art-template.js'); 
require('jqPaginator/dist/1.2.0/jqPaginator.min.js');

let actionUrl = {}




let optionsObj = {}, postObj = {}


function listInit(url, params, tplId, boxId) {
	let tbody = $(boxId).find('tbody');
	reqDefault.params = params;
	optionsObj.url = url;
	optionsObj.tbodyId = tbody.attr('id');
	postObj.params = params;
	postObj.url = url;
	postObj.tplId = tplId;
	postObj.tbody = tbody;
	
	$.ajax({
		type: 'POST',
		url: url,
		data: reqDefault,
		dataType: "json",
		success: function(res) {
			if(res.status === 1) {

				if(res.data.items.length > 0) {
					tbody.show()
					$("#datatable-paginate ul").show();
					$(".null").addClass('hide')
					if ((/datafrom/g.test(url) )|| (/dataset/g.test(url)) || (/usergroup/g.test(url))) {
						res.data.items.forEach(v => {
							let time = parseInt(v.create_at * 1000)
							v.create_at = new Date(time).format("yyyy-MM-dd");
						})
					}
					if((/crowd/g.test(url)) ) {
						res.data.items.forEach(v => {
							let time = parseInt(v.visit_time * 1000)
							v.visit_time = new Date(time).format("yyyy-MM-dd");
						})
					}
					optionsObj.count = parseInt(res.data._total.count);
					optionsObj.current = parseInt(res.data._total.page);
					
					var $html = template(tplId,res.data);
	                tbody.html($html);
	                Page.init();
				}else {
					tbody.hide()
					$("#datatable-paginate ul").hide();
					$(".null").removeClass('hide')
				}
			}
			
		}
	})
	
}


/*表格相关操作*/
$(function() {
	var EditTable = {
		options: {
			tbody: optionsObj.tbodyId || 'data-tbody'
		},
		initialize: function() {

			this.setVars().events()
		},
		setVars: function() {
			this.$tbody	= $('#'+this.options.tbody);
			return this;
		}, 
		events: function () {
			let self = this;
			this.$tbody
				.on('click', 'button.act-pause', function(e) {// 暂停操作
					e.preventDefault();
					let identify = $(this).attr('data-identify')
					let that = $(this)
					let postData = {
						identification: identify,
						token: token
					}
					$.ajax({
						type: 'POST',
						url: actionUrl.pauseUrl,
						data: postData,
						dataType: "json",
						success: function(res) {
							if(res.status === 1) {
								that.attr("data-content","数据暂停成功")
								clearTimeout(timer)
								that.popover('show')
								var timer = setTimeout(function() {
									that.popover('hide')
								},2000)
							}else {
								that.attr("data-content","发生错误，请重试")
								clearTimeout(time)
								that.popover('show')
								var time = setTimeout(function() {
									that.popover('hide')
								},2000)
							}
						}
					})
				})
				.on('click', 'button.look-detail', function(e) {
					e.preventDefault()
					let post = {
						id: $(this).attr('data-id'),
						token: token
					}
					let modalId = $(this).attr('data-target')
					$.ajax({
						type: 'POST',
						url: actionUrl.detailUrl,
						data: post,
						dataType: "json",
						success: function(res) {
							if(res.status === 1) {
								if(/tag/g.test(actionUrl.detailUrl)) {
									let time = parseInt(res.data.create_at * 1000);
									res.data.create_at = new Date(time).format("yyyy-MM-dd");
								}
 								var modalHtml = template('detail',res.data)
								$(modalId).find('div.modal-body').html(modalHtml)
							}
						}	
					})

				})
			return this;
		}
	}
	
	$(function() {
		EditTable.initialize();
			
	});
})
/*设置暂停的url*/
function setPauseUrl(url) {
	actionUrl.pauseUrl = url
}

/*设置查看详情的url*/
function setGetDetailUrl(url) {
	actionUrl.detailUrl = url
}

/*分页*/
var Page = {
	init: function() {
		var self = this;
		$.jqPaginator('#datatable-paginate ul', {
			totalCounts: optionsObj.count,
			pageSize: reqDefault.pages.page_number,
	        visiblePages: 10,
	        currentPage: optionsObj.current,
	        prev: '<li class="prev"><a href="javascript:;">Previous</a></li>',
	        next: '<li class="next"><a href="javascript:;">Next</a></li>',
	        page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
	        onPageChange: function (num, type) {
	        	if(type === 'init') {
	        	}else {
	        		self.getPageData(num);
	        	}	
	        }
	    });
	},
	getPageData: function(num) {
		reqDefault.pages.page = num;
		$.ajax({
			type: 'POST',
			url: postObj.url,
			data: reqDefault,
			dataType: "json",
			success: function(res) {
				if(res.status === 1) {
					if ((/datafrom/g.test(postObj.url) )|| (/dataset/g.test(postObj.url)) || (/usergroup/g.test(postObj.url))) {
						res.data.items.forEach(v => {
							let time = parseInt(v.create_at * 1000)
							v.create_at = new Date(time).format("yyyy-MM-dd");
						})
					}
					if((/crowd/g.test(postObj.url)) ) {
						res.data.items.forEach(v => {
							let time = parseInt(v.visit_time * 1000)
							v.visit_time = new Date(time).format("yyyy-MM-dd");
						})
					}
					optionsObj.count = parseInt(res.data._total.count);
					optionsObj.current = parseInt(res.data._total.page);
					
					var $html = template(postObj.tplId,res.data);
	                postObj.tbody.html($html);
				}
			}
		})
	}, 

}





/*格式化时间戳*/
Date.prototype.format = function(format) {
    /*
     * eg:format="YYYY-MM-dd hh:mm:ss";
     */
    var o = {
        "M+" :this.getMonth() + 1, // month
        "d+" :this.getDate(), // day
        "h+" :this.getHours(), // hour
        "m+" :this.getMinutes(), // minute
        "s+" :this.getSeconds(), // second
        "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
        "S" :this.getMilliseconds()
    // millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    }

    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                    : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}





export { reqDefault , listInit, setPauseUrl, setGetDetailUrl }